package main

import (
	"fmt"
	"github.com/go-playground/validator/v10"
)

type User struct {
	FirstName string `validate:"required"`       // 不能为空
	LastName  string `validate:"required"`       // 不能为空
	Age       uint8  `validate:"gte=0,lte=130"`  //数字在0-130之间
	Email     string `validate:"required,email"` //要求邮件格式
}

//  设置一个单例Validate
var validate *validator.Validate

func main() {
	// 初始化一个验证器
	validate = validator.New()
	// 验证结构体
	validateStruct()
}

func validateStruct() {
	user := &User{
		FirstName: "张三",
		LastName:  "",
		Age:       135,
		Email:     "2222222",
	}
	err := validate.Struct(user)
	if err != nil {
		if _, ok := err.(*validator.InvalidValidationError); ok {
			fmt.Println(err)
			return
		}
		// 验证不通过结果
		for _, err := range err.(validator.ValidationErrors) {
			fmt.Printf("验证不通过描述：%v \n", err)
		}
		return
	}
}

// 验证变量
func validateVariable() {
	myEmail := "zhangyu_techlife@163.com"
	errs := validate.Var(myEmail, "required,email")
	if errs != nil {
		fmt.Println(errs)
		return
	}
}
